<template>
  <div class="org-member-tree h100">
    <div class="treeTitleDiv" v-if="showTitle">
      <div class="treeTitle">台账结构</div>
    </div>
    <div class="filter__box" :style="{ width: showTitle ? '100%' : '70%' }">
      <!-- <el-autocomplete
        class="inline-input"
        v-model="filterText"
        sizi="mini"
        :fetch-suggestions="querySearch"
        placeholder="请输入关键字搜索"
        :trigger-on-focus="false"
        @select="handleSelect"
      ></el-autocomplete>-->
      <el-select
        ref="selectItem"
        size="mini"
        filterable
        remote
        default-first-option
        class="w100"
        v-model="filterText"
        :multiple="false"
        :placeholder="'请输入选择'"
        :remote-method="
          (query) => {
            getEquipmentBrand(query);
          }
        "
        @change="(val) => brandSelectChange(val)"
        v-loadmore="(val) => load()"
      >
        <el-option
          v-for="(optionItem, index) in option"
          :key="index"
          :label="optionItem.label"
          :value="optionItem.value"
        ></el-option>
      </el-select>
    </div>
    <div class="tree__box">
      <el-tree
        :props="props"
        @node-click="treeNodeClick"
        highlight-current
        :filter-node-method="filterNode"
        :load="loadNode"
        :data="treedata"
        :default-expanded-keys="expandKeys"
        :draggable="draggable"
        @node-drag-end="handleDragEnd"
        @check="checkClick"
        :check-strictly="checkStrictly"
        :expand-on-click-node="clickExpand"
        :node-key="nodeKey"
        :show-checkbox="showCheckbox"
        lazy
        accordion
        ref="tree"
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ data.name }}</span>
          <span>
            <el-button
              v-if="btnArr.indexOf('detail') != -1"
              type="text"
              @click.stop="() => TNodeDetail(node, data)"
              class="btnIcon"
              icon="el-icon-document"
            ></el-button>
            <el-button
              v-if="btnArr.indexOf('delete') != -1"
              type="text"
              @click.stop="() => TNodeDel(node, data)"
              class="btnIcon"
              icon="el-icon-delete"
            ></el-button>
          </span>
        </span>
      </el-tree>
    </div>
  </div>
</template>
<script>
import {
  lazyClassifyTree, //获取设备台账树
  queryList, //根据设备名称模糊查询
  getParentIdsApi, //获取某个节点的所有父节点
  getLeftUpperApi,
} from "@/api/equipmentLedger/equipmentManage";

export default {
  props: {
    itemArrs: {
      type: Array,
      default: () => {
        return [];
      },
    },
    btnArr: {
      type: Array,
      default: () => {
        return [];
      },
    },
    currentNode: {
      type: Object,
      default: () => {
        return {};
      },
    },
    filterConfig: {
      type: Object,
      default: () => {
        return {};
      },
    },
    nodeKey: {
      type: String,
      default: "id",
    },
    //展示标题
    showTitle: {
      type: Boolean,
      default: true,
    },
    //复选框限制选择的个数
    optionalNum: {
      type: Number,
      default: 0,
    },
    draggable: {
      type: Boolean,
      default: false,
    },
    //用于位置移动
    moveNode: {
      type: Boolean,
      default: false,
    },
    /* 是否点击展开 */
    clickExpand: {
      type: Boolean,
      default: false,
    },
    /* 是否显示选择框 */
    showCheckbox: {
      type: Boolean,
      default: false,
    },
    /* 是否遵循父子不互相关联的做法 */
    checkStrictly: {
      type: Boolean,
      default: false,
    },
    expandNode: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      treedata: [],
      rootNode: {},
      rootResolve: null,
      node: null,
      isChild: false,
      loadNodeData: [],
      option: [],
      count: 1,
      show: false,
      title: "添加节点",
      parentNum: 0,
      filterText: "",
      firstParentNode: "",
      props: {
        label: "name",
        children: "children",
        isLeaf: "isLeaf",
      },
      expandKeys: [],
      currentId: "",
      selectNode: {},
      toLevel: 0,
      query: "",
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
    filterLabel(val) {
      this.$refs.tree.filter(val);
    },
  },
  mounted() {},
  methods: {
    //设备列表查询
    async getEquipmentBrand(query, item) {
      this.query = query;
      if (query !== "") {
        let form = {
          name: query,
          page: 1,
          pageSize: 20,
        };
        let res = await queryList(form);
        let data = res.data.list || [];
        data.map((i) => {
          i.label = i.name;
          i.value = i.id;
        });
        this.option = data;
        this.count = 1;
      }
    },
    //设备下拉选择回传
    async brandSelectChange(val) {
      this.$forceUpdate();
      let obj = this.option.find((i) => i.value == val);
      this.option = [obj];
      this.query = "";
      this.handleSelect(obj);
    },
    //设备懒加载

    async load() {
      let form = {
        name: this.query,
        page: (this.count += 1),
        pageSize: 20,
      };
      let res = await queryList(form);
      let data = res.data.list || [];
      data.map((i) => {
        i.label = i.name;
        i.value = i.id;
      });
      this.option = this.option.concat(data);
    },
    querySearch(queryString, cb) {
      var list = [{}];
      searchByNameApi(queryString)
        .then((res) => {
          if (res.code == 200) {
            for (let i of res.data) {
              i.value = i.name; //将想要展示的数据作为value
            }
            //大小写匹配
            let restaurants = [...res.data];
            var results = queryString
              ? restaurants.filter(this.createStateFilter(queryString))
              : restaurants;
            cb(results);
          }
        })
        .catch((error) => {
          this.$message.error(error.description);
        });
    },
    createStateFilter(queryString) {
      return (state) => {
        return (
          state.value.toLowerCase().indexOf(queryString.toLowerCase()) !== -1
        );
      };
    },
    //点击搜索结果
    handleSelect(item) {
      let currentId = item.id;
      this.selectNode = item;
      this.toLevel = item.level;
      this.expandTreeNode(item);
    },
    //展开节点
    expandTreeNode(arr1, isSave) {
      getParentIdsApi(arr1.id)
        .then((res) => {
          if (res.code == 200) {
            let ids = res.data;
            ids.push(arr1.id);
            this.parentNum = res.data.length;
            let items = [];
            this.expandKeys = [];
            this.expandKeys = ids.reverse();
            if (isSave) {
              //不是第一次加载，保存数据后刷新树，数据保留到当前节点的上一层节点，同时展开父节点下的数据
              this.rootNode.childNodes = this.nextNode(
                this.rootNode.childNodes,
                1
              );
            }
            // let selectNode = this.$refs.tree.getNode(arr1.id).data;
            // this.treeNodeClick(selectNode);
          }
        })
        .catch((err) => {
          this.$message.error(err.description);
        });
    },
    //保留父节点上的数据
    nextNode(data, num) {
      let keys = this.expandKeys.reverse();
      for (let i in data) {
        if (num == this.parentNum - 1) {
          if (keys.includes(data[i]["key"])) {
            //找到父节点
            this.firstParentNode = data[i];
            data[i].childNodes = [];
            data[i].loaded = false;
            return data;
          }
        } else if (keys.includes(data[i]["key"])) {
          data[i].childNodes = this.nextNode(data[i].childNodes, num + 1);
          return data;
        }
      }
    },
    familyTree(list, id) {
      for (let i in list) {
        if (list[i].id == id) {
          return [list[i]];
        }
        if (list[i].children) {
          let node = this.familyTree(list[i].children, id);
          if (node !== undefined) {
            return node.concat(list[i]);
          }
        }
      }
    },
    //刷新懒加载的数据
    refreshLoad() {
      this.loadNodeData.forEach((item) => {
        this.loadNode(item.node, item.resolve);
      });
    },
    //确定
    doSubmit() {
      this.$refs.editFormDialog.getFormData().then((res) => {
        this.$emit("save", res);
      });
    },
    //关闭
    doClose() {
      this.show = false;
    },
    handleDragEnd(draggingNode, dropNode, dropType, ev) {
      this.$confirm("确定上移此节点吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // this.$emit("moveNode", draggingNode, dropNode);
          let draggingNodeId = draggingNode.data.id;
          let dropNodeId = dropNode.data.parentId;
          let targetId = dropNode.data.id;
          let param = {
            id: draggingNodeId,
            targetId: targetId,
            dropType: dropType,
          };
          batchUpdateDeviceTree(param)
            .then((res) => {
              if (res.code == 200) {
                let node = this.$refs.tree.getNode(dropNode.data.id); // 通过节点id找到对应树节点对象
                node.parent.loaded = false;
                node.parent.expand(); // 主动调用展开节点方法，重新查询该节点下的所有子节点
                //this.loadNode(this.node,this.resolve)
                this.$message.success(res.description);
              }
            })
            .catch((err) => {
              this.$message.error(err.description);
            });
        })
        .catch((e) => {
          let node = this.$refs.tree.getNode(dropNode.data.id); // 通过节点id找到对应树节点对象
          let dragNode = this.$refs.tree.getNode(draggingNode.data.id);
          node.parent.loaded = false;
          node.parent.expand(); // 主动调用展开节点方法，重新查询该节点下的所有子节点
          dragNode.parent.loaded = false;
          dragNode.parent.expand();
          this.$message.warning("取消移动！");
        });
    },
    //上移节点
    TNodeUp(node, data) {
      this.$emit("upNode", data);
    },
    //下移节点
    TNodeDown(node, data) {
      this.$emit("downNode", data);
    },
    //新增字节点
    TNodeAdd(node, data) {
      this.show = true;
      this.formConfigDialog.itemArr = this.itemArrs;
    },
    //编辑
    TNodeEdit(node, data) {
      this.show = true;
      this.editFormDataDialog = Object.assign({}, data);
    },
    //删除
    TNodeDel(node, data) {
      this.$confirm("此操作将删除【" + data.name + "】, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let param = {
            deleteId: data.id,
          };
          deleteFormData(param).then((res) => {
            if (res.data == 1) {
              this.currentTreeNode = {};
              this.$refs.tree.remove(data);
              this.$message.success("删除成功！");
            } else {
              this.$message.warning("无法删除非叶子节点！");
            }
          });
        })
        .catch((e) => {});
    },
    //详情
    TNodeDetail(node, data) {
      this.$emit("detail", data);
    },
    //过滤搜索
    filterNode(value, data) {
      if (value) return true;
      let label = data[this.props.label];
      return label.indexOf(value) !== -1;
    },
    //点击树节点
    treeNodeClick(node) {
      if (node) {
        this.currentId = node.id || "";
        let selectNode = this.$refs.tree.getNode(node.id).data;
        this.$refs.tree.setCurrentKey(node.id); //设置当前选择的节点
        this.$emit("handleClickTree", selectNode);
      }
    },
    //禁用树节点
    async setDisabledNode(data, resolve) {
      let parentIds = [];
      if (this.isChild) {
        //是否已经到了子层级
        if (parentIds.length == 0) {
          let res = await getParentIdsApi(data[0].id);
          parentIds = res.data || [];
        }
        if (parentIds.includes(this.currentNode.id)) {
          data.map((i) => {
            i.disabled = true;
          });
        } else {
          data.map((i) => {
            if (i.floor > this.currentNode.floor) {
              i.disabled = true;
            }
          });
        }
      } else {
        for (let item of data) {
          if (item.id == this.currentNode.id) {
            item.disabled = true;
            this.isChild = true;
            parentIds = [];
          }
          if (this.currentNode.floor) {
            if (item.floor > this.currentNode.floor) {
              item.disabled = true;
            }
          }
        }
      }
      if (resolve) {
        let treeData = [];
        data.map((i) => {
          i.label = i.name;
          i.isLeaf = i.hasChildren ? false : true;
          treeData.push(i);
        });
        resolve(treeData);
      }
      // }
      // this.$nextTick(() => {
      //   this.setTreeData(data, resolve);
      // });
    },
    //默认进来加载数据
    loadNode(node, resolve) {
      //如果展开第一级节点，从后台加载一级节点列表
      if (node.level == 0) {
        this.rootNode = node;
        this.rootResolve = resolve;
        this.loadfirstnode(resolve);
      }
      //如果展开其他级节点，动态从后台加载下一级节点列表
      if (node.level >= 1) {
        //node.level >= 1
        this.node = node;
        this.resolve = resolve;
        this.loadchildnode(node, resolve);
      }
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(this.currentId);
      });
    },
    //加载第一级节点
    loadfirstnode(resolve) {
      let form = {};
      if (JSON.stringify(this.filterConfig) != "{}") {
        if (this.filterConfig.filterConfig.length > 0) {
          form.configRules = this.filterConfig.filterConfig.join();
        }
        if (this.filterConfig.managerUnit.length > 0) {
          form.managerUnits = this.filterConfig.managerUnit.join();
        }
        if (this.filterConfig.standardType != "") {
          form.standardType = this.filterConfig.standardType;
        }
      }
      //得到组织树的数据
      lazyClassifyTree(form)
        .then((res) => {
          let data = res.data || [];
          if (this.moveNode) {
            this.setDisabledNode(data, resolve);
          } else {
            this.setTreeData(data, resolve);
          }
          //当有默认选中节点时不执行这一步
          if (this.selectNode) {
            let nodeId = this.selectNode.id || "";
            if (nodeId) {
              setTimeout(() => {
                this.treeNodeClick(this.selectNode);
              }, 200);
            } else {
              setTimeout(() => {
                this.defaultExpend(res.data[0]);
              }, 200);
            }
          } else {
            if (this.expandNode) {
              this.expandTreeNode({ id: this.expandNode });
            } else {
              setTimeout(() => {
                this.defaultExpend(res.data[0]);
              }, 200);
            }
          }
        })
        .catch((res) => {
          this.$message.error(res.description);
        });
    },
    //加载节点的子节点集合
    loadchildnode(node, resolve) {
      //得到组织树的数据
      let form = {
        parentId: node.data.id,
      };
      if (JSON.stringify(this.filterConfig) != "{}") {
        if (this.filterConfig.filterConfig.length > 0) {
          form.configRules = this.filterConfig.filterConfig.join();
        }
        if (this.filterConfig.managerUnit.length > 0) {
          form.managerUnits = this.filterConfig.managerUnit.join();
        }
        if (this.filterConfig.standardType != "") {
          form.standardType = this.filterConfig.standardType;
        }
      }
      lazyClassifyTree(form)
        .then((res) => {
          let data = res.data;
          if (this.moveNode) {
            this.setDisabledNode(data, resolve);
          } else {
            this.setTreeData(data, resolve);
          }
          //搜索选中时，加载完最后一级节点选中以选择的节点
          if (node.level == this.parentNum - 1) {
            setTimeout(() => {
              this.treeNodeClick(this.selectNode);
            }, 500);
          }
        })
        .catch((res) => {
          this.$message.error(res.description);
        });
    },
    //设备树默认展开
    defaultExpend(node) {
      let params = {
        deptId: this.$store.getters.currentInfo.currOrg,
      };
      if (
        JSON.stringify(this.filterConfig) != "{}" &&
        this.filterConfig.managerUnit.length > 0
      ) {
        params.deptId = this.filterConfig.managerUnit[0];
      }
      getLeftUpperApi(params).then((res) => {
        if (res.data) {
          if (res.data.level == 1) {
            this.updataData(res.data, true);
          } else {
            this.updataData(res.data, false);
          }
        } else {
          this.treeNodeClick(node);
        }
      });
    },
    //对数据进行处理并且设置树数据
    setTreeData(data, resolve) {
      if (resolve) {
        let treeData = [];
        data.map((i) => {
          i.label = i.name;
          i.isLeaf = i.hasChildren ? false : true;
          treeData.push(i);
        });

        setTimeout(() => {
          resolve(treeData);
        }, 100);
      }
    },
    updataData(node, isFirst) {
      let level = node ? node.level : 0;
      this.selectNode = node;
      this.expandKeys = [];
      if (!isFirst) {
        this.parentNum = level;
        if (node && level > 2) {
          //有默认节点
          this.selectNode = node;
          let isSave = isFirst ? false : true;
          this.expandTreeNode(node, isSave);
        } else {
          //第一层级的节点全部刷新
          this.rootNode.childNodes = [];
          this.loadNode(this.rootNode, this.rootResolve);
        }
      } else {
        this.treeNodeClick(node);
      }
    },
    //点击复选框时触发
    async checkClick(data, checked) {
      let checkedArr = checked.checkedKeys;
      if (this.optionalNum != 0) {
        if (checkedArr.length > this.optionalNum) {
          this.$message.warning(
            "选择的节点树不得大于限定数量" + this.optionalNum + "个！"
          );
          checkedArr = await this.arrRemove(checkedArr, data.id);
          this.$refs.tree.setCheckedKeys(checkedArr);
        }
      }
    },
    //移除掉刚选中的节点
    arrRemove(arr, key) {
      let resArr = [];
      arr.map((i) => {
        if (i != key) {
          resArr.push(i);
        }
      });
      return resArr;
    },
    //获取选中的node的Keys，用于菜单权限控制
    getCheckedKeys() {
      let halfData = this.$refs.tree.getHalfCheckedKeys(); //半选中状态的节点
      let checkedDataObj = this.$refs.tree.getCheckedNodes(); //全选中状态的节点
      let checkedData = checkedDataObj.map((i) => {
        return i.id;
      });
      let data = halfData.concat(checkedData); //合并两个数组
      return data;
    },
    getCheckedNodes() {
      let checkedDataObj = this.$refs.tree.getCheckedNodes(); //全选中状态的节点
      return checkedDataObj;
    },
  },
};
</script>
<style lang="less" scoped>
.org-member-tree .el-tree-node__content {
  border-left: 3px solid transparent;
}
.treeTitleDiv {
  text-align: left;
  padding: 20px 0 15px 0;
  .treeTitle {
    font-weight: 500;
    color: #333333;
  }
  .treeTitle:before {
    margin-right: 12px;
    width: 4px;
    height: 18px;
    background-color: #0d60b4;
    display: inline-block;
    content: "";
  }
}
/deep/.el-tree--highlight-current
  .el-tree-node.is-current
  > .el-tree-node__content {
  /*  background-color: #e9f1fe !important;
  //border-left: 3px solid #2c77f4;
  color: #2c77f4; */
}
.el-tree-node__expand-icon + .custom-tree-node {
  font-weight: 700;
}
.is-leaf + .custom-tree-node {
  font-weight: 400;
}
.org-member-tree {
  .filter__box {
    padding: 0px 0px 10px 0px;
  }
  .inline-input {
    width: 100%;
  }
  .treeInput {
    width: 100%;
  }
  .tree__box {
    height: calc(100% - 110px);
    overflow: auto;
    padding-top: 5px;
    overflow-x: auto;
    /deep/ .el-tree-node.is-expanded > .el-tree-node__children {
      display: inline;
    }
  }
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
    .el-button {
      margin-right: 10px;
      margin-left: 0px;
    }
  }
}
</style>
